<template>
  <el-form 
    :model="treeForm" 
    :rules="rules" 
    ref="treeFormRef" 
    label-width="120px" 
    style="max-width: 800px; margin: 20px auto; padding: 20px;"
  >
    <!-- 其他表单字段保持不变 -->
    <el-form-item label="古树中文名" prop="chineseName">
      <el-input v-model="treeForm.chineseName" placeholder="请输入古树中文名" />
    </el-form-item>

    <el-form-item label="拉丁学名" prop="scientificName">
      <el-input v-model="treeForm.scientificName" placeholder="请输入拉丁学名" />
    </el-form-item>

    <el-form-item label="植物科名" prop="familyName">
      <el-input v-model="treeForm.familyName" placeholder="请输入植物科名" />
    </el-form-item>

    <el-form-item label="植物属名" prop="genusName">
      <el-input v-model="treeForm.genusName" placeholder="请输入植物属名" />
    </el-form-item>

    <el-form-item label="树龄(年)" prop="estimatedAge">
      <el-input-number 
        v-model="treeForm.estimatedAge" 
        :min="0" 
        :max="65535" 
        placeholder="请输入树龄"
        controls-position="right"
      />
    </el-form-item>

    <el-form-item label="保护等级" prop="protectionLevel">
      <el-select v-model="treeForm.protectionLevel" placeholder="请选择保护等级">
        <el-option label="一级保护(树龄>500年)" :value="1" />
        <el-option label="二级保护(300<树龄<=500年)" :value="2" />
        <el-option label="三级保护(树龄<=300年)" :value="3" />
      </el-select>
    </el-form-item>

    <el-form-item label="地理位置">
      <el-cascader
        v-model="selectedArea"
        :options="regionDatas"
        :props="{ value: 'value', label: 'label', children: 'children' }"
        @change="handleChange"
        placeholder="请选择省市区"
        style="width: 100%"
      />
    </el-form-item>

    <el-form-item label="经度" prop="gpsLongitude">
      <el-input v-model="treeForm.gpsLongitude" placeholder="请输入经度（如：116.3912345）" />
    </el-form-item>

    <el-form-item label="纬度" prop="gpsLatitude">
      <el-input v-model="treeForm.gpsLatitude" placeholder="请输入纬度（如：39.9076543）" />
    </el-form-item>

    <el-form-item label="详细地址" prop="locationAddress">
      <el-input 
        v-model="treeForm.locationAddress" 
        type="textarea" 
        placeholder="请输入详细地理位置描述"
        :rows="3"
      />
    </el-form-item>
    <el-form-item label="地理位置选择">
    <el-button type="primary" @click="openMapSelector">在地图上选择位置</el-button>
  </el-form-item>

    <el-form-item label="古树描述" prop="description">
      <el-input 
        v-model="treeForm.description" 
        type="textarea" 
        placeholder="请输入古树历史或特征描述"
        :rows="4"
      />
    </el-form-item>

    <el-form-item label="古树图片">
      <el-upload
        v-model:file-list="imageList"
        list-type="picture-card"
        :action="uploadUrl"
        name="file"
        multiple
        :data="uploadData"
        :headers="{ 'authentication': tokenStore.token }"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>
    </el-form-item>

    <el-form-item>
  <el-button 
    type="primary" 
    @click="submitForm" 
    :loading="submitting"
  >
    {{ submitting ? '提交中...' : '提交' }}
  </el-button>
  <el-button @click="resetForm">重置</el-button>
</el-form-item>
  </el-form>
  <el-dialog
    v-model="mapDialogVisible"
    title="选择地理位置"
    width="80%"
    height="80%"
    :before-close="handleMapDialogClose"
  >
    <div class="map-selector-container">
      <div ref="mapSelectorRef" class="map-selector"></div>
      <div class="map-info-panel">
        <h4>选点信息</h4>
        <p>经度: {{ selectedLng }}</p>
        <p>纬度: {{ selectedLat }}</p>
        <p>地址: {{ selectedAddress }}</p>
        <el-button type="primary" @click="confirmLocation" :disabled="!selectedLng || !selectedLat">
          确认选择
        </el-button>
      </div>
    </div>
  </el-dialog>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, nextTick, onBeforeUnmount } from 'vue';
import { regionData, CodeToText } from 'element-china-area-data'; 
import { Plus } from '@element-plus/icons-vue';
import { ElMessage,ElMessageBox  } from 'element-plus';
import { addTree } from '@/apis/treeAPI';
import { useAuthStore } from '@/stores/auth/userAuthStore';
import { useRouter } from 'vue-router'; // 添加路由导入

const tokenStore = useAuthStore();
const router = useRouter();

// 提交状态
const submitting = ref(false);

const treeFormRef = ref();
const selectedArea = ref([]);
const regionDatas = ref(regionData);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
const imageList = ref([]);




// 地图选点相关
const mapDialogVisible = ref(false);
const mapSelectorRef = ref(null);
let mapSelector = null;
let markerSelector = null;
const selectedLng = ref('');
const selectedLat = ref('');
const selectedAddress = ref('');

// 打开地图选点弹窗
const openMapSelector = () => {
  if (navigator.geolocation) {
    ElMessage.info('正在获取您的位置...');
    navigator.geolocation.getCurrentPosition(
      (position) => {
        const { latitude, longitude } = position.coords;
        // 保存当前位置，用于初始化地图
        selectedLat.value = latitude.toFixed(7);
        selectedLng.value = longitude.toFixed(7);
        
        mapDialogVisible.value = true;
        nextTick(() => {
          initMapSelector(latitude, longitude);
        });
      },
      (error) => {
        console.error('获取位置失败:', error);
        ElMessage.warning('获取位置失败，将使用默认位置');
        mapDialogVisible.value = true;
        nextTick(() => {
          initMapSelector(); // 使用默认位置
        });
      },
      {
        enableHighAccuracy: true,
        timeout: 10000,
        maximumAge: 60000
      }
    );
  } else {
    ElMessage.error('您的浏览器不支持地理定位');
    mapDialogVisible.value = true;
    nextTick(() => {
      initMapSelector(); // 使用默认位置
    });
  }
};

// 初始化地图选点
const initMapSelector = (lat = 40, lng = 116) => {
  if (!mapSelectorRef.value) return;
  
  // 如果地图已存在，先销毁
  if (mapSelector) {
    mapSelector.destroy();
  }
  
  // 创建地图实例，使用传入的坐标或默认坐标
  const center = new TMap.LatLng(lat, lng);
  mapSelector = new TMap.Map(mapSelectorRef.value, {
    zoom: 15, // 定位时使用更近的缩放级别
    center: center
  });
  
  // 创建标记图层
  markerSelector = new TMap.MultiMarker({
    map: mapSelector,
    geometries: [{
      id: 'selectedMarker',
      position: center
    }]
  });
  
  // 如果是通过定位获取的坐标，同时获取地址信息
  if (lat !== 40 || lng !== 116) {
    getAddressFromLatLng(center);
  }
  
  // 添加点击事件
  mapSelector.on('click', (event) => {
    const latlng = event.latLng;
    selectedLat.value = latlng.getLat().toFixed(7);
    selectedLng.value = latlng.getLng().toFixed(7);
    
    // 更新标记位置
    markerSelector.updateGeometries([{
      id: 'selectedMarker',
      position: latlng
    }]);
    
    // 获取地址信息
    getAddressFromLatLng(latlng);
  });
};
// 根据经纬度获取地址信息

const getAddressFromLatLng = (latlng) => {
  try {
    // 检查TMap是否正确加载
    if (!window.TMap || !window.TMap.service) {
      console.error('TMap service not available');
      selectedAddress.value = '地图服务不可用';
      return;
    }
    
    const geocoder = new TMap.service.Geocoder();
    
    // 添加超时处理
    const timeoutPromise = new Promise((_, reject) => {
      setTimeout(() => reject(new Error('请求超时')), 5000);
    });
    
    const geocodePromise = geocoder.getAddress({
      location: latlng
    });
    
    // 使用Promise.race处理超时
    Promise.race([geocodePromise, timeoutPromise])
      .then((result) => {
        console.log('Geocoder result:', result);
        if (result.status === 0) {
          selectedAddress.value = result.result.address || '';
        } else {
          console.error('Geocoder error status:', result.status);
          selectedAddress.value = '获取地址失败，错误码: ' + result.status;
        }
      })
      .catch((error) => {
        console.error('Geocoder error:', error);
        selectedAddress.value = '获取地址失败: ' + error.message;
      });
  } catch (error) {
    console.error('Error in getAddressFromLatLng:', error);
    selectedAddress.value = '获取地址异常: ' + error.message;
  }
};
// 确认选择位置
const confirmLocation = () => {
  treeForm.gpsLongitude = selectedLng.value;
  treeForm.gpsLatitude = selectedLat.value;
  treeForm.locationAddress = selectedAddress.value;
  mapDialogVisible.value = false;
};

// 关闭地图弹窗
const handleMapDialogClose = () => {
  mapDialogVisible.value = false;
};

// 组件卸载前清理地图
onBeforeUnmount(() => {
  if (mapSelector) {
    mapSelector.destroy();
    mapSelector = null;
  }
});



// 上传相关配置
const uploadUrl = '/api/uploadFile'; // 使用多文件上传接口
const uploadData = computed(() => {
  return {
    path: 'trees' // 指定存储路径为 trees 目录
  };
});

// 表单数据模型
const treeForm = reactive({
  chineseName: '',
  scientificName: '',
  familyName: '',
  genusName: '',
  estimatedAge: 0,
  protectionLevel: null,
  gpsLongitude: '',
  gpsLatitude: '',
  provinceCode: '',
  provinceName: '',
  cityCode: '',
  cityName: '',
  districtCode: '',
  districtName: '',
  locationAddress: '',
  description: '',
  images: []
});

// 表单验证规则
const rules = {
  chineseName: [
    { required: true, message: '中文名不能为空', trigger: 'blur' },
    { max: 50, message: '中文名长度不能超过50字符', trigger: 'blur' }
  ],
  familyName: [
    { required: true, message: '科名不能为空', trigger: 'blur' },
    { max: 50, message: '科名长度不能超过50字符', trigger: 'blur' }
  ],
  genusName: [
    { required: true, message: '属名不能为空', trigger: 'blur' },
    { max: 50, message: '属名长度不能超过50字符', trigger: 'blur' }
  ],
  protectionLevel: [
    { required: true, message: '保护等级不能为空', trigger: 'change' }
  ],
  locationAddress: [
    { required: true, message: '地理位置不能为空', trigger: 'blur' },
    { max: 1000, message: '地理位置描述过长', trigger: 'blur' }
  ],
  description: [
    { max: 2000, message: '描述内容超过2000字符限制', trigger: 'blur' }
  ],
gpsLongitude: [
  { required: true, message: '经度不能为空', trigger: 'blur' },
  { pattern: /^-?((\d{1,2}(\.\d{1,7})?)|(1[0-7]\d(\.\d{1,7})?)|(180(\.0{1,7})?))$/, message: '经度格式不正确，范围应在-180到180之间', trigger: 'blur' }
],
gpsLatitude: [
  { required: true, message: '纬度不能为空', trigger: 'blur' },
  { pattern: /^-?(([0-8]?\d(\.\d{1,7})?)|(90(\.0{1,7})?))$/, message: '纬度格式不正确，范围应在-90到90之间', trigger: 'blur' }
]
};

// 处理省市区选择变化

const handleChange = (value) => {
  console.log('Selected area values:', value);
  if (value && value.length >= 3) {
    treeForm.provinceCode = value[0];
    treeForm.cityCode = value[1];
    treeForm.districtCode = value[2];
    
    console.log('Code to text mapping:', CodeToText);
    console.log('Province code:', value[0]);
    console.log('City code:', value[1]);
    
    // 增加安全检查，防止访问未定义属性
    treeForm.provinceName = CodeToText[value[0]] || '';
    treeForm.cityName = CodeToText[value[1]] || '';
    treeForm.districtName = CodeToText[value[2]] || '';
  }
};


/* const handleChange = (value) => {
  if (value && value.length >= 3) {
    treeForm.provinceCode = value[0];
    treeForm.cityCode = value[1];
    treeForm.districtCode = value[2];
    
    treeForm.provinceName = codeToText[value[0]];
    treeForm.cityName = codeToText[value[1]];
    treeForm.districtName = codeToText[value[2]];
  }
};
 */
// 图片预览
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  dialogVisible.value = true;
};

// 移除图片
const handleRemove = (uploadFile, uploadFiles) => {
  console.log('Removed file:', uploadFile);
};

// 上传成功处理
const handleUploadSuccess = (response, uploadFile, uploadFiles) => {
  console.log('Upload success:', response);
  ElMessage.success('图片上传成功');
};

// 上传失败处理
const handleUploadError = (error, uploadFile, uploadFiles) => {
  console.error('Upload error:', error);
  ElMessage.error('图片上传失败');
};

// 提交表单
const submitForm = async () => {
  // 防止重复提交
  if (submitting.value) return;
  
  try {
    const valid = await treeFormRef.value.validate();
    if (valid) {
      submitting.value = true; // 设置提交状态
      
      // 提取图片URL
      treeForm.images = imageList.value.map(item => item.response ? item.response.data : item.url || '');
      const result = await addTree(treeForm);
     
      if(result.code === 1){
        ElMessage.success('添加成功');
        
        // 显示选择框，让用户选择下一步操作
        ElMessageBox.confirm(
          '您可以选择返回首页查看列表，或者继续添加新的古树信息。',
          '添加成功',
          {
            confirmButtonText: '返回首页',
            cancelButtonText: '继续添加',
            type: 'success',
            center: true
          }
        )
        .then(() => {
          // 用户选择返回首页
          router.push('/'); // 根据实际首页路径调整
        })
        .catch(() => {
          // 用户选择继续添加
          resetForm();
        });
      } else {
        ElMessage.error('添加失败: ' + (result.message || '未知错误'));
      }
    } else {
      console.log('表单验证失败');
    }
  } catch (error) {
    console.error('表单提交出错:', error);
    ElMessage.error('提交失败，请稍后重试');
  } finally {
    submitting.value = false; // 重置提交状态
  }
};
// 重置表单
const resetForm = () => {
  treeFormRef.value.resetFields();
  selectedArea.value = [];
  imageList.value = [];
};
</script>

<style scoped>
.el-form {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.map-selector-container {
  display: flex;
  height: 500px;
}

.map-selector {
  flex: 1;
  height: 100%;
}

.map-info-panel {
  width: 250px;
  padding: 20px;
  border-left: 1px solid #ebeef5;
  background-color: #f5f7fa;
}

.map-info-panel h4 {
  margin-top: 0;
  margin-bottom: 20px;
}

.map-info-panel p {
  margin: 10px 0;
}

</style>